<template>
  <div>
    <audio v-if="audioURL" :src="audioURL" controls></audio>
    <div>
      <p v-for="(item, index) in items" :key="index">
        译文：<strong>{{ item.zh }}</strong>
        <br>
        原文：<strong>{{ item.en }}</strong>
      </p>
      <button @click="startStreaming">开始识别</button>
      <button @click="endStream">停止识别</button>
    </div>
    <div>待翻译数据{{ base64Queue.length }}</div>
  </div>
</template>


<script>

export default {
  name: "translate",
  data() {
    return {
      ws: null,
      mediaRecorder: null,
      audioChunks: [],
      userId: null,
      audioURL: null,
      msgIndex: 0 ,
      needStart: true ,
      timeoutTaskNo: null ,
      msgData: {
        type: 2,
        sessionId: null,
        msgContent: null,
      },
      base64Queue: [],// 待确认是否处理完成
      realDom: [], //已翻译完的消息
      items: [],//翻译结果
    };
  },
  created() {
    this.userId = this.$store.state.user.userInfo.userId;
  },
  methods: {
    connectWebSocket: function () {
      this.ws = new WebSocket('ws://localhost:8106/ws/test'); // 修改为你的WebSocket服务器地址和端口
      this.ws.onopen = () => {
        console.log('Connected to WebSocket server');
      };
      this.ws.onmessage = (event) => {
        let msg = JSON.parse(event.data);
        if (msg.type === 1) {
          this.msgData.sessionId = msg.sessionId;
        } else if (msg.type === 3) {
          this.addItem(msg.msgContent);
        }
      };
      this.ws.onerror = (error) => {
        console.error('WebSocket error:', error);
      };
      this.ws.onclose = () => {
        console.log('Disconnected from WebSocket server');
      };
    },
    startStreaming() {
      navigator.mediaDevices.getUserMedia({audio: true})
        .then(stream => {
          this.mediaRecorder = new MediaRecorder(stream);
          this.mediaRecorder.ondataavailable = e => this.audioChunks.push(e.data);
          this.mediaRecorder.start();
          this.timeoutTaskNo = window.setTimeout(this.stopRecording,10000);
        })
        .catch(error => console.error('Error accessing the media devices.', error));
    },
    stopRecording() {

      if (this.mediaRecorder) {
        this.mediaRecorder.stop();
        this.mediaRecorder.onstop = () => {
          const audioBlob = new Blob(this.audioChunks, {type: 'audio/wav'});
          this.audioURL = URL.createObjectURL(audioBlob);
          const reader = new FileReader();
          reader.readAsDataURL(audioBlob); // 转换为Base64编码的DataURL格式的字符串。
          reader.onloadend = () => {

            // 这是Base64编码的音频数据。
            this.msgData.msgContent = {
              "baseData": reader.result,
              "msgNo": this.generateUniqueId(),
              "sort": this.msgIndex,
              "userId": this.userId
            }

            //放到待处理缓冲池中
            this.base64Queue.push(this.msgData.msgContent);
            this.ws.send(JSON.stringify(this.msgData)); // 发送Base64编码的音频数据。
            this.audioChunks = []; // 重置chunks数组。
            this.msgIndex +=1;
            if (this.needStart){
              this.startStreaming();
            }
            // console.log(this.msgIndex)
            // console.log(this.msgData.msgContent)
          };
        };
      } else {
        console.error('MediaRecorder is not initialized.');
      }
    },
    generateUniqueId() {
      let timestamp = new Date().getTime();
      let randomNum = Math.random().toString(36).substr(2, 9);
      return this.userId + '-' + timestamp + '-' + randomNum;
    },
    /**
     * 渲染翻译结果
     */
    addItem(dataList) {

      //渲染完的消息先放到完成翻译的池子里去，后面如果全句翻译有改变的话方便调整
      // this.realDom.push(this.msgData.msgContent.msgNo);
      for (let i = 0; i < dataList; i++) {
        console.log(dataList[i]);
      }
      let content = {
        "zh": `中文${this.items.length + 1}`,
        "en": `英文${this.items.length + 1}`,
      }
      this.items.push(content);
    },
    /**
     * 终结翻译流程 将不会开始继续翻译
     */
    endStream(){
      this.needStart = false;
      if (this.timeoutTaskNo !== null){
        window.clearTimeout(this.timeoutTaskNo);
        this.timeoutTaskNo = null;
      }
      this.stopRecording();
    }
  },
  mounted() {
    this.connectWebSocket(); // 组件挂载后连接WebSocket。
  },
  beforeDestroy() {
    if (this.ws) {
      this.ws.close(); // 组件销毁前关闭WebSocket连接。
    }
  }
};
</script>
<style scoped>
</style>
